import cv2 as cv
from PIL import Image
import pytesseract  # 要配置tesseract-ocr 引擎的
from io import BytesIO  # 操作二进制文件


def recognize_text(src):
    gray = cv.cvtColor(src, cv.COLOR_BGR2GRAY)
    ret, binary = cv.threshold(
        gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (1, 6))  # 去除线
    binl = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel)
    kernel = cv.getStructuringElement(cv.MORPH_RECT, (5, 1))
    open_out = cv.morphologyEx(binl, cv.MORPH_OPEN, kernel)
    cv.bitwise_not(open_out, open_out)  # 黑色背景变为白色背景
    # cv.imshow('open_out', open_out)

    # 从np.array 转换成<class 'PIL.Image.Image'>，pytesseract需要接受此类型
    textImage = Image.fromarray(open_out)
    text = pytesseract.image_to_string(textImage)

    print(text)

    print("This OK:%s" % text)
    return text

# 验证码识别


def distinguish(filename):

    # src = cv.imread(filename)
    # src = BytesIO(src)
    src = Image.open(filename)

    gray = src.convert('L')
    # 图像对象转化（L：8位像素，表示黑和白）
    # 可以参考：Python图像处理库PIL的基本概念介绍 - icamera0的博客 - CSDN博客
    # 如果RGB数值小于140的变成1，否则是255。也就是将验证码背景变成白色，具体字符变成黑色。
    bw = gray.point(lambda x: 0 if x < 140 else 255, '1')

    text = pytesseract.image_to_string(bw)
    return text.replace(' ', '').replace('.', '')
    # return recognize_text(src)


if __name__ == "__main__":
    text = distinguish('checkCode.jpg')
    print(text)
